// 企业内部开发相关
package gdingtalk

import (
	"errors"
	"github.com/tidwall/gjson"
)

type Corp struct {
	option    string
	appKey    string
	appSecret string
	agentId   int64
	corpId    string
}

// NewCorp 初始化
func NewCorp(option string) (Corp, error) {
	_json := gjson.Parse(option)
	return Corp{
		option:    option,
		appKey:    _json.Get("appKey").String(),
		appSecret: _json.Get("appSecret").String(),
		agentId:   _json.Get("agentId").Int(),
		corpId:    _json.Get("corpId").String(),
	}, nil
}

// GetAccessToken 获取access_token
func (__ *Corp) GetAccessToken(corpId string) (string, error) {
	// 优先判断缓存
	t, err := gCache.cGet("access_token_" + __.corpId)
	if err == nil && t != "" {
		return t, nil
	}
	res := Get().
		SetPath("/gettoken").
		AddQueryParam("appkey", __.appKey).
		AddQueryParam("appsecret", __.appSecret).
		Do()
	if res.IsSuccess() {
		token := res.GetBody("access_token").String()
		// 回写到缓存
		gCache.cPut("access_token_"+__.corpId,
			token,
			res.GetBody("expires_in").Int()-200,
		)
		return token, nil
	} else {
		return "", errors.New(res.GetErrmsg())
	}
}

// GetAgentId 获取agentId
func (__ *Corp) GetAgentId(corpId string) (int64, error) {
	return __.agentId, nil
}
